﻿namespace EFS.RC.CommunicatorContext.Resources
{
	public static class Caching
	{
		// cached sources
		private static System.Collections.Generic.Dictionary<System.String, System.Object> cachedResources =
			new System.Collections.Generic.Dictionary<System.String, System.Object>();

		/// <summary>
		/// cache all
		/// </summary>
		public static void MakeCache()
		{
			// get resources
			System.Reflection.PropertyInfo[] propertyInfoArray = typeof(EFS.RC.CommunicatorContext.Resources.Common).GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

			// load all and cache
			foreach (System.Reflection.PropertyInfo propertyInfo in propertyInfoArray)
			{
				Add(propertyInfo.GetValue(null, null), propertyInfo.Name);
			}
		}

		/// <summary>
		/// Add
		/// </summary>
		/// <param name="bitmap"></param>
		private static void Add(System.Object data, System.String uniqueName)
		{
			// only if not null
			if (null == data)
			{
				return;
			}

			// check
			if (!cachedResources.ContainsKey(uniqueName))
			{
				// cachle
				cachedResources[uniqueName] = data;
			}
		}

		/// GetByteData
		public static System.Byte[] GetByteData(System.String uniqueName)
		{
			if (!cachedResources.ContainsKey(uniqueName))
			{
				return null;
			}

			// test if stream
			System.Object retValue = cachedResources[uniqueName];
			if (retValue is System.Byte[])
			{
			}
			else if (retValue is System.IO.Stream)
			{
				System.IO.Stream stream = retValue as System.IO.Stream;
				System.IO.MemoryStream ms = new System.IO.MemoryStream();
				stream.CopyTo(ms);
				retValue = ms.ToArray();
				stream.Close();
				ms.Close();
			}
			else
			{
				retValue = null;
			}

			// ok
			return retValue as System.Byte[];
		}
	}

}